package com.topone.controller;

import com.topone.Enum.ResultEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Form.CouponOrderForm;
import com.topone.Form.OrderPayForm;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dataObject.TcCoupon;
import com.topone.dto.OrderDTO;
import com.topone.dto.TcUserCouponDTO;
import com.topone.repository.TcCouponRepository;
import com.topone.service.BuyerService;
import com.topone.service.OrderService;
import com.topone.service.TcUserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2017/12/5,0005.
 */
@RestController
@RequestMapping("/buyer/order")
@Slf4j
@CrossOrigin
public class BuyerOrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private BuyerService buyerService;
    @Autowired
    private TcCouponRepository tcCouponRepository;
    @Autowired
    private TcUserCouponService tcUserCouponService;

    @PostMapping("/create")
    public ResultVO<Map<String, Object>> create(@Valid CouponOrderForm orderForm,
                                                @RequestParam("returnUrl") String returnUrl,
                                                BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确orderForm={}", orderForm);
            return ResultVOUntil.error(1, bindingResult.getFieldError()
                    .getDefaultMessage());
        }
        //计算判断优惠券支付价格
        Map<String, Object> map = orderService.calculateAmount(orderForm.getCouponId(),
                orderForm.getCouponNum(), orderForm.getCouponPrice(), orderForm.getOrderAmount());
        if ("error".equals(map.get("flag"))) {
            ResultVO resultVO = (ResultVO) map.get("error");
            log.info("计算支付价格失败,{}", resultVO);
            return resultVO;
        }
        //限领优惠券数目
        TcCoupon tcCoupon = tcCouponRepository.getOne(orderForm.getCouponId());
        if (tcCoupon.getCouponNumLimit() != null && tcCoupon.getCouponNumLimit() > 0) {
            TcUserCouponDTO tcUserCoupon = new TcUserCouponDTO();
            tcUserCoupon.setBuyerOpenid(orderForm.getBuyerOpenid());
            tcUserCoupon.setCouponId(orderForm.getCouponId());
            List<TcUserCouponDTO> list =
                    tcUserCouponService.findCouponByopenidAndCouponId(tcUserCoupon);
            Integer num = 0;
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getCouponNum() != null && list.get(i).getCouponNum() > 0) {
                    num += list.get(i).getCouponNum();
                }
            }

            log.debug("已购买数目:", num);
            if (tcCoupon.getCouponNumLimit() <
                    (num + Integer.parseInt(orderForm.getCouponNum()))) {
                log.error("无法再购买券。已超出领券限额");
                return ResultVOUntil.error(1, "无法再购买券。已超出领券限额");
            }
        }

        OrderDTO orderDTO;
        try {
            orderDTO = orderService.create(orderForm);
        } catch (FanZoneException e) {
            log.error("【创建订单】创建订单失败 e={}", e.fillInStackTrace());
            return ResultVOUntil.error(1, ResultEnum.ORDER_CREATE_ERROR.getMessage());
        }
        //免费优惠券不需要支付
        Double amount = Double.valueOf(orderForm.getOrderAmount());
        if (amount == 0) {
            //修改订单的支付状态
            try {
                orderDTO = orderService.paid(orderService.findOne(orderDTO.getOrderId()));
            } catch (Exception e) {
                log.debug("免费优惠券，领取失败");
                return ResultVOUntil.error(1, e.fillInStackTrace().toString());
            }
            log.info("免费优惠券,直接领取,{}", orderDTO);
            map.put("success", "领取成功");
            return ResultVOUntil.success(map);
        } else {
            log.info("start to purchase coupon");
            return ResultVOUntil.success(orderService.purchaseCoupon(orderDTO,tcCoupon.getBussinessId()));
        }
    }

    //再次唤起支付
    @PostMapping("/purchaseCoupon")
    public ResultVO<Map<String, Object>> create(@RequestBody OrderPayForm orderPayForm){
        OrderDTO orderDTO=orderService.findOne(orderPayForm.getOrderId());
         if(Objects.nonNull(orderDTO) && orderPayForm.getOpenid().equals(orderDTO.getBuyerOpenid())){
             return ResultVOUntil.success(orderService.purchaseCoupon(orderDTO,orderPayForm.getBusinessId()));
         }else{
             return ResultVOUntil.error(1,"该用户无改订单信息");
         }

    }

    //查询订单列表
    @GetMapping("/list")
    public ResultVO<List<OrderDTO>> list(@RequestParam("openid") String openid,
                                         @RequestParam(value = "page", defaultValue = "0") Integer page,
                                         @RequestParam(value = "size", defaultValue = "10") Integer size) {


        if (StringUtils.isEmpty(openid)) {
            log.error("【查询订单列表】 openid为空");
            throw new FanZoneException(ResultEnum.PARAM_ERROR);
        }
        Pageable pageable = new PageRequest(page, size);
        Page<OrderDTO> orderDTOPage = orderService.findList(openid, pageable);

        return ResultVOUntil.success(orderDTOPage);
    }

    //查询订单详情
    @GetMapping("/detail")
    public ResultVO<OrderDTO> detail(@RequestParam("orderId") String orderId,
                                     @RequestParam("openid") String openid) {

        OrderDTO orderDTO = buyerService.findOrderOne(orderId, openid);
        return ResultVOUntil.success(orderDTO);
    }

    //订单取消
    @PostMapping("/cancel")
    public ResultVO cancel(@RequestParam("openid") String openid,
                           @RequestParam("orderid") String orderid) {
        buyerService.cancelOrderOne(orderid, openid);
        return ResultVOUntil.success();
    }

    //用户未支付订单
    @GetMapping("/unpay")
    public ResultVO<Map<String, Object>> unpay(@RequestParam("openid") String openid,
                                               Map<String, Object> map) {

        if (StringUtils.isEmpty(openid)) {
            log.info("{}", "openid 为空");
            return ResultVOUntil.error(1, "openid为空");
        }
        List<OrderDTO> orderDTOList = orderService.findUnpayOrderList(openid);
        map.put("orderDTOList", orderDTOList);
        log.info("用户未支付订单查询成功,{},{}", openid, map);
        return ResultVOUntil.success(map);
    }

}
